package com.hjf.booking.module.user.controller;


import com.alibaba.fastjson.JSONObject;
import com.hjf.booking.constants.BaseResponse;
import com.hjf.booking.module.user.dto.WxUser;
import com.hjf.booking.module.user.service.MpUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hjf
 * @since 2021-02-18
 */
@RestController
@RequestMapping("/user")
public class MpUserController {

    @Autowired
    private MpUserService mpUserService;


    /**
     * 登录，接收coke响应token
     *
     * @param code
     * @return
     */
    @GetMapping("/login")
    public BaseResponse login(@RequestParam("code") String code) {
        JSONObject jsonObject = mpUserService.getOpenid(code);
        String openId = jsonObject.getString("openid");
        String sessionKey = jsonObject.getString("session_key");
        if (openId == null) {
            if (code.startsWith("openid-") && code.length() > 30) {
                openId = code.substring(7);
            } else {
                return BaseResponse.bad(jsonObject.getString("errmsg"));
            }
        }
        return mpUserService.login(openId);
    }

    @PostMapping("/complete")
    public BaseResponse completeInfo(@RequestBody WxUser wxUser,
                                     @RequestParam("openid") String openid){
        wxUser.setOpenid(openid);
        return mpUserService.completeInfo(wxUser);
    }


}

